package com.dkts.oil.util.gis;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;

public class GeoUtils {
    public static GeometryFactory geometryFactory = new GeometryFactory();

    public static String getGeoWkr(JSONObject jsonObject){
        if(jsonObject == null){
            return null;
        }
        String type = jsonObject.getString("type");
        if(StringUtils.isBlank(type)){
            return null;
        }

        JSONArray jsonArray = jsonObject.getJSONArray("coordinates");
        if (jsonArray == null){
            return null;
        }

        switch (type){
            case "Point":
                return geometryFactory.createPoint(new Coordinate(jsonArray.getDouble(0),jsonArray.getDouble(1))).toText();
            case "LineString":
                 int row = jsonArray.size();
                 Coordinate[] coordinates = new Coordinate[row];
                 for (int i = 0; i < row; i++) {
                     JSONArray jsonArray1 = jsonArray.getJSONArray(i);
                     coordinates[i] = new Coordinate(jsonArray1.getDouble(0),jsonArray1.getDouble(1));
                 }
                return geometryFactory.createLineString(coordinates).toText();
            case "Polygon":
               JSONArray jsonArray1=  jsonArray.getJSONArray(0);
               int row1 = jsonArray1.size();
               Coordinate[] coordinates1 = new Coordinate[row1];
               for (int i = 0; i < row1; i++) {
                   JSONArray jsonArray2 = jsonArray1.getJSONArray(i);
                   coordinates1[i] = new Coordinate(jsonArray2.getDouble(0),jsonArray2.getDouble(1));
               }
               return geometryFactory.createLineString(coordinates1).toText();
            }
        return null;
    }

    public static void main(String[] args) {
        String point = "{\"coordinates\":[116.390359,39.876508],\"type\":\"Point\"}";
        String lineString = "{\"coordinates\":[[116.540067,39.771054],[116.541141,39.769733]],\"type\":\"LineString\"}";
        String polygon = "{\"coordinates\":[[[116.419052,39.95391],[116.419136,39.95393],[116.420065,39.953912],[116.420153,39.95195],[116.419118,39.951947],[116.41901,39.953838],[116.419052,39.95391]]],\"type\":\"Polygon\"}";
        System.out.println(getGeoWkr(JSONObject.parseObject(point)));
        System.out.println(getGeoWkr(JSONObject.parseObject(lineString)));
        System.out.println(getGeoWkr(JSONObject.parseObject(polygon)));

    }
}

